package com.qf.openapi.web.master.intercepter;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Contants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class AutoLogininterceptor implements HandlerInterceptor {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //1.判断 如果session有user对象，直接重定向palteform
        HttpSession session = request.getSession();
        User sessionuser = (User) session.getAttribute(Contants.SESSION_USER_KEY);

        if (sessionuser!=null){
            log.debug("用户已经登录过了，直接重定向到首页");
            response.sendRedirect("/plateform.html");
            return false;
        }

        //2.检查请求中是否有usertoken——cookie ，有的话返回用户登录状态
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Contants.USER_TOKEN)) {
                    String usertokenvalue = cookie.getValue();
                    String[] split = usertokenvalue.split("-");
                    String username=split[0];
                    String md5password=split[1];

                    //还原用户登录状态
                    User user = userService.restoreUser(username,md5password);

                    //把user对象放入session中
                    session.setAttribute(Contants.SESSION_USER_KEY,user);

                    //重定向plateform
                    log.debug("根据cookie还原用户登录状态成功user={}",user);
                    response.sendRedirect("/plateform.html");
                    return false;
                }
            }
        }
        log.debug("没有免登录的cookie进入登录页面");
        return true;
    }
}
